<script setup>
import dayjs from 'dayjs';
import { find } from 'lodash-es';
import { useMain } from '@/store/app.js';
import { useRequest, useWatch } from '@/hooks';
import { dateFormat } from '@/utils/index.js';
import { alarmStastic, getEngTypesByCode } from '@/api/index';
import EnergyType from '@/components/EnergyType.vue';
import AreaForm from '@/views/components/AreaForm.vue';
import CECharts from '@/components/chart/CECharts.vue';

const { proxy } = getCurrentInstance();
const { projectType } = useMain();
const themeToggleStyle = {
  'theme-dark': {
    curMth: {
      color: '#f5f5f5',
      backgroundColor: '#161e35',
    },
    notCurMth: {
      color: '#545864',
      backgroundColor: '#202637',
      // border: '1px solid #232e4a',
    },
  },
  'theme-light': {
    curMth: {
      // color: '#fff',
      // backgroundColor: '#1fa3d2',
      // border: '1px solid #74a3b4',
    },
    notCurMth: {
      color: 'rgba(255,255,255,0.8)',
      backgroundColor: '#c1c1c1',
      // border: '1px solid #a5a5a5',
    },
  },
};
const radio = ref(projectType);
const month = ref(dayjs().toDate());
const reset = ref(0);
const energyType = ref('ELECTRICITY');
const inId = ref('');
const CRDom = ref(null);
const CLHeight = ref(0);
const pieOptions = ref({
  color: ['#76e612', '#efef12', '#e87f16', '#e61c1c'],
  title: [
    {
      text: '',
      textStyle: { fontSize: 36, color: '#fff' },
      left: 'center',
      top: '35%',
      itemGap: 4,
      subtext: '能源使用超标天数',
      subtextStyle: { fontWeight: 'normal', fontSize: 14, color: '#e5eaf3' },
    },
    {
      subtext: '（天）',
      subtextStyle: { fontWeight: 'normal', fontSize: 14, color: '#e5eaf3' },
      left: 'center',
      top: '52%',
    },
  ],
  legend: [
    {
      type: 'scroll',
      show: true,
      orient: 'vertical',
      bottom: '15%',
      right: 0,
      itemWidth: 18,
      itemHeight: 10,
      itemStyle: { borderWidth: 0 },
      textStyle: { color: '#7f889a' },
    },
  ],
  tooltip: {
    formatter: params => `${params.name}: ${params.value} (天)`,
    // position: ['60%', '20%'],
  },
  series: [
    {
      type: 'pie',
      radius: ['60%', '80%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center',
      },
      // emphasis: {
      //   label: {
      //     show: true,
      //     fontSize: 40,
      //     fontWeight: 'bold'
      //   }
      // },
      labelLine: {
        show: false,
      },
      data: [],
      top: 0,
      bottom: 0,
    },
  ],
});
const [engTypeList, , runEngType] = useRequest(getEngTypesByCode, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      let id = res.data?.[0]?.id ?? null;
      if (id === 1) {
        energyType.value = 'WATER';
      } else if (id === 2) {
        energyType.value = 'ELECTRICITY';
      } else if (id === 3) {
        energyType.value = 'AIR';
      } else if (id === 4) {
        energyType.value = 'WARM';
      }
      searchQuery();
    }
  },
});
const [res, loading, run] = useRequest(alarmStastic, {
  manual: true,
  onSuccess: res => {
    let arr = res?.data?.pieData?.map(n => ({ name: n.energyName, value: n.overDay }));
    pieOptions.value.series[0].data = arr;
    pieOptions.value.title[0].text = res?.data?.totalOverDays ?? '';
  },
});
const searchQuery = () => {
  run({
    month: dateFormat(month.value, 'YYYY-MM'),
    inId: inId.value,
    projectType: radio.value,
    energyType: energyType.value,
  });
};
const addMonth = () => {
  month.value = dayjs(month.value).add(1, 'month').toDate();
  searchQuery();
};
const subtractMonth = () => {
  month.value = dayjs(month.value).subtract(1, 'month').toDate();
  searchQuery();
};

const engChange = val => {
  if (val === 1) {
    energyType.value = 'WATER';
  } else if (val === 2) {
    energyType.value = 'ELECTRICITY';
  } else if (val === 3) {
    energyType.value = 'AIR';
  } else if (val === 4) {
    energyType.value = 'WARM';
  }
  searchQuery();
};
const handleQuery = queryParams => {
  // dateFormat(month.value, 'YYYY-MM')
  inId.value = queryParams?.buildingCode?.enterpriseCode;
  runEngType({ enterpriseCode: inId.value, projectType: radio.value, allType: false });
};
const resetQuery = queryParams => {
  // inId.value = queryParams?.buildingCode?.enterpriseCode;
  // searchQuery();
};
const itemDayDisplay = day => {
  let arr = res.value?.calendarData ?? [];
  const dayObj = find(arr, v => v.day == day);
  return dayObj;
};
useWatch(
  radio,
  n => {
    reset.value = reset.value + 1;
  },
  { immediate: true },
);
useWatch(
  () => proxy.$store.state.global.setting.sideTheme,
  n => {
    if (n === 'theme-dark') {
      pieOptions.value.title[0].textStyle.color = '#fff';
      pieOptions.value.title[0].subtextStyle.color = '#e5eaf3';
      pieOptions.value.title[1].subtextStyle.color = '#e5eaf3';
    } else {
      pieOptions.value.title[0].textStyle.color = '#000';
      pieOptions.value.title[0].subtextStyle.color = '#999';
      pieOptions.value.title[1].subtextStyle.color = '#999';
    }
  },
  { immediate: true },
);
onMounted(() => {
  CLHeight.value = CRDom.value.clientHeight;
});
</script>

<template>
  <div class="app-container">
    <div class="u-df-st u-base-fg u-pl20 u-mb20">
      <el-radio-group v-model="radio" size="small" class="radio">
        <el-radio-button label="JC">监测机构</el-radio-button>
        <el-radio-button label="TG">托管机构</el-radio-button>
      </el-radio-group>
      <AreaForm
        ref="areaFormRef"
        :projectType="radio"
        :reset="reset"
        :propParams="true"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
        :isStage="true"
        :showType="radio === 'TG' ? true : false"
        style="margin-bottom: 0px"
      />
    </div>
    <div class="u-base-fg u-ptb10 u-plr20 u-df-spb u-mb20">
      <span>能源使用情况统计</span>
      <div class="u-df-ct">
        <i class="el-icon-arrow-left" @click="subtractMonth"></i>
        <span class="c-date">
          {{ dateFormat(month, 'YYYY-MM') }}
        </span>
        <i class="el-icon-arrow-right" @click="addMonth"></i>
      </div>
    </div>
    <div class="u-df-spb" style="height: calc(100% - 168px); align-items: flex-start">
      <div class="u-base-fg u-p20 c-left" :style="{ height: CLHeight + 'px' }">
        <div>各项能源超标天数占比统计</div>
        <div style="height: 300px; margin-top: 30px">
          <CECharts v-loading="loading" type="pie" :options="pieOptions" />
        </div>
        <el-table v-if="radio === 'TG'" v-loading="loading" :data="res?.pieData ?? []" border>
          <el-table-column prop="energyName" label="能源类型" align="center" />
          <el-table-column prop="date" label="日期(月份)" align="center" />
          <el-table-column prop="overDay" label="超标天数" align="center" show-overflow-tooltip />
          <el-table-column prop="overQuantity" label="超标总量" align="center" show-overflow-tooltip />
          <el-table-column prop="monthBasis" label="月度基准" align="center" show-overflow-tooltip />
          <el-table-column prop="monthAvg" label="月度平均" align="center" show-overflow-tooltip />
          <el-table-column prop="energyUnit" label="能源单位" align="center" />
        </el-table>
        <el-table v-else v-loading="loading" :data="res?.pieData ?? []" border>
          <el-table-column prop="energyName" label="能源类型" align="center" />
          <el-table-column prop="date" label="日期(月份)" align="center" />
          <el-table-column prop="overDay" label="超标天数" align="center" show-overflow-tooltip />
          <el-table-column prop="overUpQuantity" label="超过约束值" align="center" show-overflow-tooltip />
          <el-table-column prop="overQuantity" label="超过基准值" align="center" show-overflow-tooltip />
          <el-table-column prop="monthAvg" label="月度平均" align="center" show-overflow-tooltip />
          <el-table-column prop="energyUnit" label="能源单位" align="center" />
        </el-table>
        <div class="u-df-st u-mt20" style="align-items: flex-start; padding-bottom: 5px; margin-top: 30px">
          <i class="el-icon-warning text-warning" style="margin-right: 8px"></i>
          <div>
            <div class="u-mb10 u-fs12" style="font-weight: 400">提示</div>
            <div class="u-fs12 u-sec-text c-tooltip">
              能源使用基准值为年度设定，平均至每日进行监测跟踪用能情况。月度分析能源使用情况，本月当前用能累计量除以当前天数得出用能值，用能值高于日基准，说明能源使用率降低，影响相关收益。建议：分析高耗能环节，进行控制。
            </div>
          </div>
        </div>
      </div>
      <div ref="CRDom" class="c-right">
        <div class="u-df-spb" style="height: 50px; margin-bottom: 10px">
          <div class="u-h100 u-df-spb u-base-fg u-ptb10 u-plr20" style="width: calc(50% - 5px)">
            能耗超标趋势日历
            <div class="u-df-st u-fs11">
              <div class="u-circular" style="background: #30943a"></div>
              基准用能
              <div class="u-circular" style="background: #e62b2b; margin-left: 27px"></div>
              能耗超标
            </div>
          </div>
          <div class="u-h100 u-df-spb u-base-fg u-plr20" style="width: calc(50% - 5px); font-size: 14px">
            <EnergyType :engList="engTypeList" @changeType="engChange" />
          </div>
        </div>
        <el-calendar v-loading="loading" v-model="month" class="as-calendar">
          <template slot="dateCell" slot-scope="{ data }">
            <div v-if="data.type === 'current-month'" class="u-h100 u-df-ct u-fd-col">
              <div class="u-w100 u-h100 text-center">
                <div v-if="itemDayDisplay(data.day)?.color === 2" class="u-h100 bg-orange">
                  <span style="display: block; height: 26%">{{ itemDayDisplay(data.day)?.day?.slice(8, 10) }}</span>
                  <span class="u-fs14">{{ itemDayDisplay(data.day)?.overQuantity }}/{{ res?.energyUnit }}</span>
                </div>
                <div v-if="itemDayDisplay(data.day)?.color === 1" class="u-h100 bg-red">
                  <span style="display: block; height: 26%">{{ itemDayDisplay(data.day)?.day?.slice(8, 10) }}</span>
                  <span class="u-fs14">{{ itemDayDisplay(data.day)?.overQuantity }}/{{ res?.energyUnit }}</span>
                </div>
                <div v-else-if="itemDayDisplay(data.day)?.color === 0" class="bg-green">
                  {{ itemDayDisplay(data.day)?.day?.slice(8, 10) }}
                </div>
                <div v-else-if="!itemDayDisplay(data.day)?.color" class="bg-black">
                  {{ itemDayDisplay(data.day)?.day?.slice(8, 10) }}
                </div>
              </div>
            </div>
            <div
              v-else
              class="u-df-ct u-h100"
              :style="themeToggleStyle[$store.state.global.setting.sideTheme].notCurMth"
            >
              {{ dateFormat(data.day, 'D') }}
            </div>
          </template>
        </el-calendar>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.u-ptb10 {
  padding-top: 10px;
  padding-bottom: 10px;
}

.u-plr20 {
  padding-left: 20px;
  padding-right: 20px;
}

.c-date {
  font-family: DIN, DIN;
  font-weight: bold;
  font-size: 19px;
  margin: 0 20px;
}

.c-tooltip {
  line-height: 24px;
  font-weight: 300;
}

.c-left {
  width: calc(40% - 10px);
}

.c-right {
  width: calc(60% - 10px);
}

.u-circular {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin: 2px 3px;
}

.el-icon-arrow-left,
.el-icon-arrow-right {
  font-size: 10px;
  cursor: pointer;
}

.as-calendar :deep(.el-calendar__header) {
  display: none;
}

.bg-green {
  background-color: #30943a;
}

.bg-red {
  background-color: #e62b2b;
}

.bg-orange {
  background-color: #c98a1b;
}

.bg-black {
  background-color: rgb(32, 38, 55);
}

:deep(.el-calendar__body) {
  padding: 0;
}

:deep(.el-calendar-table thead th:before) {
  content: '星期';
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 88px;
  line-height: 88px;
}

:deep(.el-calendar-table td.is-selected) {
  background-color: unset;
}

.as-calendar :deep(.el-calendar-table .el-calendar-day:hover),
.as-calendar :deep(.el-calendar-table td.is-selected) {
  background-color: unset !important;
}
</style>
